<template>
  <div class="data-analysis-container fade-in">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h2 class="page-title">
            <el-icon class="title-icon">
              <DataAnalysis />
            </el-icon>
            数据分析
          </h2>
          <p class="page-subtitle">深度数据洞察和智能分析报告</p>
        </div>
        <div class="header-actions">
          <el-button type="primary" plain @click="generateReport">
            <el-icon><Document /></el-icon>
            生成报告
          </el-button>
          <el-button type="success" @click="exportAnalysis">
            <el-icon><Download /></el-icon>
            导出分析
          </el-button>
        </div>
      </div>
    </div>

    <!-- 分析概览 -->
    <div class="analysis-overview">
      <el-row :gutter="24">
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="analysis-card" shadow="hover">
            <div class="analysis-content">
              <div class="analysis-icon">
                <el-icon><TrendCharts /></el-icon>
              </div>
              <div class="analysis-info">
                <div class="analysis-number">{{ growthRate }}%</div>
                <div class="analysis-label">增长率</div>
                <div class="analysis-trend">
                  <el-icon class="trend-icon up"><ArrowUp /></el-icon>
                  <span class="trend-text">+{{ monthlyGrowth }}%</span>
                  <span class="trend-period">本月</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="analysis-card" shadow="hover">
            <div class="analysis-content">
              <div class="analysis-icon">
                <el-icon><User /></el-icon>
              </div>
              <div class="analysis-info">
                <div class="analysis-number">{{ conversionRate }}%</div>
                <div class="analysis-label">转化率</div>
                <div class="analysis-trend">
                  <el-icon class="trend-icon up"><ArrowUp /></el-icon>
                  <span class="trend-text">+{{ conversionGrowth }}%</span>
                  <span class="trend-period">本月</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="analysis-card" shadow="hover">
            <div class="analysis-content">
              <div class="analysis-icon">
                <el-icon><Money /></el-icon>
              </div>
              <div class="analysis-info">
                <div class="analysis-number">¥{{ avgRevenue }}</div>
                <div class="analysis-label">平均收入</div>
                <div class="analysis-trend">
                  <el-icon class="trend-icon up"><ArrowUp /></el-icon>
                  <span class="trend-text">+{{ revenueGrowth }}%</span>
                  <span class="trend-period">本月</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="analysis-card" shadow="hover">
            <div class="analysis-content">
              <div class="analysis-icon">
                <el-icon><Star /></el-icon>
              </div>
              <div class="analysis-info">
                <div class="analysis-number">{{ satisfactionScore }}</div>
                <div class="analysis-label">满意度</div>
                <div class="analysis-trend">
                  <el-icon class="trend-icon up"><ArrowUp /></el-icon>
                  <span class="trend-text">+{{ satisfactionGrowth }}%</span>
                  <span class="trend-period">本月</span>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 高级图表分析 -->
    <div class="advanced-charts">
      <el-row :gutter="24">
        <!-- 预测分析 -->
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="chart-header">
                <h3>收入预测分析</h3>
                <el-select v-model="predictionPeriod" placeholder="预测周期" size="small">
                  <el-option label="未来30天" value="30"></el-option>
                  <el-option label="未来90天" value="90"></el-option>
                  <el-option label="未来180天" value="180"></el-option>
                </el-select>
              </div>
            </template>
            <v-chart class="chart" :option="predictionChartOption" autoresize />
          </el-card>
        </el-col>

        <!-- 用户行为分析 -->
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="chart-header">
                <h3>用户行为分析</h3>
                <el-button type="primary" size="small" @click="refreshBehaviorData">
                  <el-icon><Refresh /></el-icon>
                  刷新
                </el-button>
              </div>
            </template>
            <v-chart class="chart" :option="behaviorChartOption" autoresize />
          </el-card>
        </el-col>

        <!-- 地理分布分析 -->
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="chart-header">
                <h3>地理分布分析</h3>
                <el-tag type="info">{{ totalRegions }} 个地区</el-tag>
              </div>
            </template>
            <v-chart class="chart" :option="geographicChartOption" autoresize />
          </el-card>
        </el-col>

        <!-- 时间序列分析 -->
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card" shadow="hover">
            <template #header>
              <div class="chart-header">
                <h3>时间序列分析</h3>
                <el-select v-model="timeSeriesMetric" placeholder="选择指标" size="small">
                  <el-option label="报名人数" value="entries"></el-option>
                  <el-option label="收入金额" value="income"></el-option>
                  <el-option label="完成率" value="completion"></el-option>
                </el-select>
              </div>
            </template>
            <v-chart class="chart" :option="timeSeriesChartOption" autoresize />
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 智能洞察 -->
    <div class="insights-section">
      <el-card class="insights-card" shadow="hover">
        <template #header>
          <div class="insights-header">
            <h3>智能洞察</h3>
            <el-button type="primary" size="small" @click="generateInsights">
                              <el-icon><Star /></el-icon>
              生成洞察
            </el-button>
          </div>
        </template>
        <div class="insights-content">
          <div v-for="(insight, index) in insights" :key="index" class="insight-item">
            <div class="insight-icon">
              <el-icon :class="insight.type">
                <component :is="insight.icon" />
              </el-icon>
            </div>
            <div class="insight-content">
              <div class="insight-title">{{ insight.title }}</div>
              <div class="insight-description">{{ insight.description }}</div>
              <div class="insight-metrics">
                <el-tag v-for="metric in insight.metrics" :key="metric.label" :type="metric.type" size="small">
                  {{ metric.label }}: {{ metric.value }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 生成报告对话框 -->
    <el-dialog 
      v-model="showReportDialog" 
      title="生成分析报告" 
      width="600px" 
      class="report-dialog"
      :close-on-click-modal="false">
      <div class="report-content">
        <div class="report-description">
          <p>请选择要包含在报告中的分析内容：</p>
        </div>
        
        <div class="report-options">
          <el-checkbox-group v-model="selectedReports" class="report-checkbox-group">
            <el-checkbox value="overview" class="report-option">
              <div class="report-option-content">
                <div class="report-icon">
                  <el-icon><TrendCharts /></el-icon>
                </div>
                <div class="report-text">
                  <div class="report-title">概览分析</div>
                  <div class="report-desc">包含关键指标和趋势分析</div>
                </div>
              </div>
            </el-checkbox>
            
            <el-checkbox value="prediction" class="report-option">
              <div class="report-option-content">
                <div class="report-icon">
                  <el-icon><DataAnalysis /></el-icon>
                </div>
                <div class="report-text">
                  <div class="report-title">预测分析</div>
                  <div class="report-desc">未来趋势预测和风险评估</div>
                </div>
              </div>
            </el-checkbox>
            
            <el-checkbox value="behavior" class="report-option">
              <div class="report-option-content">
                <div class="report-icon">
                  <el-icon><User /></el-icon>
                </div>
                <div class="report-text">
                  <div class="report-title">行为分析</div>
                  <div class="report-desc">用户行为模式和偏好分析</div>
                </div>
              </div>
            </el-checkbox>
            
            <el-checkbox value="insights" class="report-option">
              <div class="report-option-content">
                <div class="report-icon">
                  <el-icon><Star /></el-icon>
                </div>
                <div class="report-text">
                  <div class="report-title">智能洞察</div>
                  <div class="report-desc">AI生成的业务洞察和建议</div>
                </div>
              </div>
            </el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showReportDialog = false">取消</el-button>
          <el-button type="primary" @click="handleGenerateReport" :loading="generating">
            <el-icon><Document /></el-icon>
            生成报告
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, BarChart, PieChart, ScatterChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent,
  VisualMapComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import { 
  DataAnalysis, Document, Download, TrendCharts, User, Money, Star,
  ArrowUp, ArrowDown, Refresh, Warning
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// 注册 ECharts 组件
use([
  CanvasRenderer,
  LineChart,
  BarChart,
  PieChart,
  ScatterChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent,
  DataZoomComponent,
  VisualMapComponent
])

// 响应式数据
const predictionPeriod = ref('90')
const timeSeriesMetric = ref('entries')
const showReportDialog = ref(false)
const selectedReports = ref(['overview', 'prediction'])
const generating = ref(false)

// 模拟数据
const growthRate = ref(15.8)
const monthlyGrowth = ref(2.3)
const conversionRate = ref(68.5)
const conversionGrowth = ref(1.2)
const avgRevenue = ref(1250.50)
const revenueGrowth = ref(5.7)
const satisfactionScore = ref(4.6)
const satisfactionGrowth = ref(0.3)
const totalRegions = ref(12)

// 智能洞察数据
const insights = ref([
  {
    type: 'success',
    icon: 'TrendCharts',
    title: '收入增长趋势良好',
    description: '本月收入较上月增长15.8%，主要得益于篮球和足球比赛的报名人数增加。建议继续保持当前的营销策略。',
    metrics: [
      { label: '增长率', value: '+15.8%', type: 'success' },
      { label: '主要贡献', value: '篮球比赛', type: 'info' }
    ]
  },
  {
    type: 'warning',
    icon: 'Warning',
    title: '转化率有待提升',
    description: '虽然报名人数增加，但转化率仅为68.5%，低于行业平均水平。建议优化报名流程和用户体验。',
    metrics: [
      { label: '当前转化率', value: '68.5%', type: 'warning' },
      { label: '行业平均', value: '75.2%', type: 'info' }
    ]
  },
  {
    type: 'info',
    icon: 'User',
    title: '用户满意度稳定',
    description: '用户满意度评分为4.6分，处于良好水平。用户反馈显示对比赛组织和流程安排较为满意。',
    metrics: [
      { label: '满意度', value: '4.6/5.0', type: 'success' },
      { label: '反馈数量', value: '156条', type: 'info' }
    ]
  }
])

// 图表配置
const predictionChartOption = computed(() => {
  const days = parseInt(predictionPeriod.value)
  const historicalData = []
  const predictedData = []
  
  for (let i = 0; i < days; i++) {
    const date = new Date()
    date.setDate(date.getDate() - days + i)
    const dateStr = date.toISOString().slice(0, 10)
    
    if (i < days * 0.7) {
      historicalData.push([dateStr, Math.floor(Math.random() * 5000) + 2000])
    } else {
      predictedData.push([dateStr, Math.floor(Math.random() * 5000) + 2000])
    }
  }

  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['历史数据', '预测数据']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: historicalData.map(item => item[0]).concat(predictedData.map(item => item[0]))
    },
    yAxis: {
      type: 'value',
      name: '收入金额 (元)'
    },
    series: [
      {
        name: '历史数据',
        type: 'line',
        smooth: true,
        data: historicalData.map(item => item[1]),
        itemStyle: { color: '#5470c6' }
      },
      {
        name: '预测数据',
        type: 'line',
        smooth: true,
        data: new Array(historicalData.length).fill(null).concat(predictedData.map(item => item[1])),
        itemStyle: { color: '#91cc75' },
        lineStyle: { type: 'dashed' }
      }
    ]
  }
})

const behaviorChartOption = computed(() => ({
  tooltip: {
    trigger: 'item'
  },
  legend: {
    orient: 'vertical',
    left: 'left'
  },
  series: [
    {
      name: '用户行为',
      type: 'pie',
      radius: '50%',
      data: [
        { value: 45, name: '直接报名', itemStyle: { color: '#5470c6' } },
        { value: 25, name: '浏览后报名', itemStyle: { color: '#91cc75' } },
        { value: 20, name: '推荐报名', itemStyle: { color: '#fac858' } },
        { value: 10, name: '其他渠道', itemStyle: { color: '#ee6666' } }
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
}))

const geographicChartOption = computed(() => ({
  tooltip: {
    trigger: 'item'
  },
  legend: {
    orient: 'vertical',
    left: 'left'
  },
  series: [
    {
      name: '地区分布',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '18',
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: [
        { value: 35, name: '北京', itemStyle: { color: '#5470c6' } },
        { value: 28, name: '上海', itemStyle: { color: '#91cc75' } },
        { value: 22, name: '广州', itemStyle: { color: '#fac858' } },
        { value: 15, name: '深圳', itemStyle: { color: '#ee6666' } }
      ]
    }
  ]
}))

const timeSeriesChartOption = computed(() => {
  const data = []
  const now = new Date()
  for (let i = 29; i >= 0; i--) {
    const date = new Date(now)
    date.setDate(date.getDate() - i)
    data.push({
      date: date.toISOString().slice(0, 10),
      entries: Math.floor(Math.random() * 50) + 10,
      income: Math.floor(Math.random() * 5000) + 1000,
      completion: Math.floor(Math.random() * 30) + 70
    })
  }

  const metricMap = {
    entries: { name: '报名人数', data: data.map(item => item.entries) },
    income: { name: '收入金额', data: data.map(item => item.income) },
    completion: { name: '完成率', data: data.map(item => item.completion) }
  }

  const selectedMetric = metricMap[timeSeriesMetric.value]

  return {
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.map(item => item.date),
      axisLabel: { rotate: 45 }
    },
    yAxis: {
      type: 'value',
      name: selectedMetric.name
    },
    series: [
      {
        name: selectedMetric.name,
        type: 'line',
        smooth: true,
        data: selectedMetric.data,
        itemStyle: { color: '#5470c6' },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(84, 112, 198, 0.3)' },
              { offset: 1, color: 'rgba(84, 112, 198, 0.1)' }
            ]
          }
        }
      }
    ]
  }
})

// 方法
const generateReport = () => {
  showReportDialog.value = true
}

const exportAnalysis = () => {
  ElMessage.success('分析报告导出成功')
}

const refreshBehaviorData = () => {
  ElMessage.success('行为数据已刷新')
}

const generateInsights = () => {
  ElMessage.success('智能洞察已更新')
}

const handleGenerateReport = async () => {
  if (selectedReports.value.length === 0) {
    ElMessage.warning('请至少选择一个报告内容')
    return
  }

  generating.value = true
  try {
    // 模拟报告生成
    await new Promise(resolve => setTimeout(resolve, 2000))
    ElMessage.success('分析报告生成成功')
    showReportDialog.value = false
  } catch (error) {
    ElMessage.error('报告生成失败')
  } finally {
    generating.value = false
  }
}

onMounted(() => {
  // 初始化数据
})
</script>

<style scoped>
.data-analysis-container {
  padding: var(--spacing-lg);
  background: var(--bg-primary);
  min-height: 100vh;
}

.page-header {
  margin-bottom: var(--spacing-xl);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: var(--spacing-lg);
}

.title-section {
  flex: 1;
}

.page-title {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
  font-size: 1.75rem;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 var(--spacing-sm) 0;
}

.title-icon {
  font-size: 1.5rem;
  color: var(--primary-color);
}

.page-subtitle {
  color: var(--text-secondary);
  font-size: 0.9rem;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: var(--spacing-md);
}

/* 分析概览 */
.analysis-overview {
  margin-bottom: var(--spacing-xl);
}

.analysis-card {
  border-radius: var(--radius-lg);
  transition: all 0.3s ease;
}

.analysis-card:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-lg);
}

.analysis-content {
  display: flex;
  align-items: center;
  gap: var(--spacing-lg);
}

.analysis-icon {
  width: 60px;
  height: 60px;
  border-radius: var(--radius-lg);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.5rem;
  color: white;
  background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
}

.analysis-info {
  flex: 1;
}

.analysis-number {
  font-size: 1.75rem;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: var(--spacing-xs);
}

.analysis-label {
  color: var(--text-secondary);
  font-size: 0.9rem;
  margin-bottom: var(--spacing-sm);
}

.analysis-trend {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
}

.trend-icon {
  font-size: 0.8rem;
}

.trend-icon.up {
  color: var(--success-color);
}

.trend-icon.down {
  color: var(--danger-color);
}

.trend-text {
  font-size: 0.8rem;
  font-weight: 500;
}

.trend-period {
  font-size: 0.7rem;
  color: var(--text-secondary);
}

/* 高级图表 */
.advanced-charts {
  margin-bottom: var(--spacing-xl);
}

.chart-card {
  border-radius: var(--radius-lg);
  transition: all 0.3s ease;
  margin-bottom: var(--spacing-lg);
}

.chart-card:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-lg);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-header h3 {
  margin: 0;
  color: var(--text-primary);
  font-size: 1.1rem;
  font-weight: 600;
}

.chart {
  height: 350px;
  width: 100%;
}

/* 智能洞察 */
.insights-section {
  margin-bottom: var(--spacing-xl);
}

.insights-card {
  border-radius: var(--radius-lg);
}

.insights-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.insights-header h3 {
  margin: 0;
  color: var(--text-primary);
  font-size: 1.1rem;
  font-weight: 600;
}

.insights-content {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-lg);
}

.insight-item {
  display: flex;
  gap: var(--spacing-md);
  padding: var(--spacing-lg);
  background: var(--bg-secondary);
  border-radius: var(--radius-lg);
  transition: all 0.3s ease;
}

.insight-item:hover {
  background: var(--bg-hover);
  transform: translateX(4px);
}

.insight-icon {
  width: 48px;
  height: 48px;
  border-radius: var(--radius-lg);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.25rem;
  color: white;
  flex-shrink: 0;
}

.insight-icon.success {
  background: linear-gradient(135deg, var(--success-color), var(--success-dark));
}

.insight-icon.warning {
  background: linear-gradient(135deg, var(--warning-color), var(--warning-dark));
}

.insight-icon.info {
  background: linear-gradient(135deg, var(--info-color), var(--info-dark));
}

.insight-content {
  flex: 1;
}

.insight-title {
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: var(--spacing-sm);
  font-size: 1rem;
}

.insight-description {
  color: var(--text-secondary);
  font-size: 0.9rem;
  margin-bottom: var(--spacing-md);
  line-height: 1.5;
}

.insight-metrics {
  display: flex;
  gap: var(--spacing-sm);
  flex-wrap: wrap;
}

/* 报告对话框 */
.report-dialog {
  border-radius: var(--radius-xl);
}

.report-content {
  padding: var(--spacing-lg) 0;
}

.report-description p {
  margin: 0 0 var(--spacing-lg) 0;
  color: var(--text-primary);
  font-size: 0.9rem;
}

.report-options {
  margin-bottom: var(--spacing-lg);
}

.report-checkbox-group {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-md);
}

.report-option {
  margin: 0 !important;
  padding: var(--spacing-md);
  border: 2px solid var(--border-color);
  border-radius: var(--radius-lg);
  transition: all 0.3s ease;
}

.report-option:hover {
  border-color: var(--primary-color);
  background: rgba(99, 102, 241, 0.05);
}

.report-option.is-checked {
  border-color: var(--primary-color);
  background: rgba(99, 102, 241, 0.1);
}

.report-option-content {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
}

.report-icon {
  width: 48px;
  height: 48px;
  border-radius: var(--radius-lg);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.25rem;
  color: white;
  background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
}

.report-text {
  flex: 1;
}

.report-title {
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: var(--spacing-xs);
}

.report-desc {
  font-size: 0.8rem;
  color: var(--text-secondary);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .data-analysis-container {
    padding: var(--spacing-md);
  }

  .header-content {
    flex-direction: column;
    align-items: flex-start;
  }

  .header-actions {
    width: 100%;
    justify-content: flex-start;
  }

  .analysis-content {
    flex-direction: column;
    text-align: center;
    gap: var(--spacing-md);
  }

  .analysis-icon {
    width: 50px;
    height: 50px;
    font-size: 1.25rem;
  }

  .chart {
    height: 250px;
  }

  .insight-item {
    flex-direction: column;
    text-align: center;
  }

  .insight-icon {
    align-self: center;
  }

  .report-option-content {
    flex-direction: column;
    text-align: center;
    gap: var(--spacing-sm);
  }

  .report-icon {
    width: 40px;
    height: 40px;
    font-size: 1rem;
  }
}

@media (max-width: 480px) {
  .page-title {
    font-size: 1.5rem;
  }

  .analysis-number {
    font-size: 1.5rem;
  }

  .chart {
    height: 200px;
  }
}
</style>
